<template>
    <div id="app">
        <el-headr>
            <!-- 定义对外部通讯的prop参数 -->
            <HeaderPage :avatar="avatar" :nick_name="nick_name" :is_admin="isAdmin"></HeaderPage>
        </el-headr>
        <div><h5  class="page_title"><el-button link @click="goto_user_center"> &lt;返回</el-button> &nbsp;我的账单</h5> </div>

        <el-tabs v-model="tab_active_name" @tab-click="handleChangeView">
            <div>
                <el-row>
                    <el-select v-model="period_value" 
                    class="m-2" placeholder="选择账单周期"
                    @change="selectPeriod(period_value)">
                        <el-option
                          v-for="item in months"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                      <el-select v-model="direction_value" 
                      class="m-2" placeholder="选择收支方向"
                      @change="selectDirection(direction_value)">
                        <el-option
                          v-for="item in direction"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                </el-row>
                <el-row class="charge_summary">
                    <span class="summarize">本期总计收入:{{formatted_total_income}}</span>
                    <span class="summarize">本期总计消耗:{{formatted_total_spend}}</span>
                </el-row>
            </div>
                
            <el-tab-pane label="现金账单" :ref="cash_pane" name="cash">
                <el-table :data="cash_transcation_set" 
                height="80dvh">
                    <el-table-column prop="transcation_id" label="交易流水ID" width=""></el-table-column>
                    <el-table-column prop="transcation_amount" label="交易金额" width=""></el-table-column>
                    <el-table-column prop="order_id" label="订单ID" width=""></el-table-column>
                    <el-table-column prop="transcation_type" label="交易类型" width=""></el-table-column>
                    <el-table-column prop="transcation_direction" label="交易方向" width=""></el-table-column>
                    <el-table-column prop="transcation_date" label="交易时间" width=""></el-table-column>
                </el-table>
            </el-tab-pane>

            <el-tab-pane label="优惠券账单" :ref="coupon_pane" name="coupon">
                <el-table :data="coupon_transcation_set" 
                height="80dvh">
                    <el-table-column prop="transcation_id" label="交易流水ID" width=""></el-table-column>
                    <el-table-column prop="transcation_amount" label="交易金额" width=""></el-table-column>
                    <el-table-column prop="order_id" label="订单ID" width=""></el-table-column>
                    <el-table-column prop="transcation_type" label="交易类型" width=""></el-table-column>
                    <el-table-column prop="transcation_direction" label="交易方向" width=""></el-table-column>
                    <el-table-column prop="transcation_date" label="交易时间" width=""></el-table-column>
                </el-table>

            </el-tab-pane>  
        </el-tabs>

        <div v-if="total_page_size" >
            <el-pagination 
            @current-change="pageChange" 
            :current-page.sync="current_page"
            layout="prev, pager, next"
            :page-size=page_size
            :page-count=total_page_size
            :page-sizes="[1,10,30,50]"
            >
        </el-pagination>

        </div>
        <FooterPage style="margin:40dvh 40dvw "></FooterPage>
    </div>
     </template>
     
     <script>
     import HeaderPage from '@/components/HeaderPage.vue'
     import FooterPage from '@/components/FooterPage.vue'
     import { ElNotification,ElTable,ElTableColumn,ElPagination,ElMessage, ElMessageBox } from 'element-plus';
     import { ref, watch } from 'vue';
     import config from '../../spoken.config.json';
   

     export default{
         name:'MyBill',
         components:{
            HeaderPage,
            FooterPage,
            ElTable,ElTableColumn,ElPagination,
        },
       
         data(){
             return{
                    userData:{},
                    nick_name:null,
                    avatar:null,
                    user_id:null,
                    tab_active_name:'cash',
                    direction:[{value:'0',label:'全部'},{value:'1',label:'收入'},{value:'2',label:'支出'}],
                    months:[],
                    page:1,
                    page_size:config.PAGE_SIZE,
                    total_page_size:null,
                    period_value:null,
                    direction_value:null,
                    cash_transcation_set:[],
                    coupon_transcation_set:[],
                    total_spend:0,
                    total_income:0,
                    isAdmin:false,
                };
         },
         created(){
            this.user_profiles();
            this.get_months();
         },
        
         mounted(){
            console.log("mounted时候的user_id： "+this.user_id)
         },

        
         watch:{
            //监听数据变化
            userData:{
            //数据变化的时候会自动调用handler函数，并自动填充newData参数
                handler(newData){
                    this.nick_name=newData.nick_name;
                    this.avatar=newData.avatar;
                },
                deep:true, // 深度监听对象内部属性的变化
            },
         },
         
         computed:{
            formatted_total_income(){
                 return Number(this.total_income).toFixed(2)
            },
            formatted_total_spend(){
                return Number(this.total_spend).toFixed(2)
            }
         },
       
        methods:{
            goto_user_center(){
                this.$router.push({ path: '/user_center/' });
            },
            //页面初始化
        async user_profiles(){
                const login_token= this.$commonFunctions.get_cookies('login_token')
                console.log("用户中心初始化数据。login_token："+login_token);
                if(login_token!=null){
                    const user_profiles= await this.$commonFunctions.get_user_profiles(login_token);
                    //更新userData数据，触发watch的钩子
                    this.userData.nick_name=user_profiles.name;
                    this.userData.avatar=user_profiles.avatar;
                    this.user_id=user_profiles.user_id;
                    this.isAdmin=user_profiles.is_superuser
                    console.log("用户中心初始化数据。user_id： "+this.user_id+" 下一步获取推荐码");
                    const rcode=await this.$commonFunctions.get_promotion_code(this.user_id)
                    console.log("获取推荐码接口的返回值： "+JSON.stringify(rcode));
                    this.promotion_code=rcode.promotion_code;
                }else{
                    ElNotification({
                            message: "您太长时间没有动作，为保证安全请重新登录",
                            title: "系统消息",
                            type: "info",
                            duration: 3000,
                        });
                        this.$router.push("/");
                }
                
            },
    
        nick_name_focus(){
                this.nick_name_active=true;
            },
        nick_name_blur(){
                this.nick_name_active=false;
            },

        handleChangeView(tab,event){
               console.log("tab="+tab," event="+event)
               this.cash_transcation_set=[]
               this.coupon_transcation_set=[]
               this.period_value=null
               this.direction_value=null
            },
            
        get_months(){
                console.log("准备生成月份数据")
                const date=new Date();
                console.log("当前基准日期"+date);
                const month=date.getMonth()+1;
                this.months=[{value:month,label:month+"月"}, {value:month-1,label:month-1+"月"},{value:month-2,label:month-2+"月"}]
                console.log(this.months)
            },
            
        pageChange(val){
                console.log(val)
                this.page=val
                this.get_bill()
            },
            
        selectDirection(){
                this.coupon_transcation_set=[]
                this.cash_transcation_set=[]
                this.total_income=0
                this.total_spend=0
                this.get_bill();
            },
            
        selectPeriod(){
                this.coupon_transcation_set=[]
                this.cash_transcation_set=[]
                this.total_income=0
                this.total_spend=0
                this.get_bill();
            },
        
        async get_bill(){
             if (true){
                console.log(this.tab_active_name)
                if(this.direction_value!==null){
                    if(this.tab_active_name==="cash"){
                        const data={
                                        "table_type":1,
                                        "period":this.period_value,
                                        "direction":this.direction_value,
                                        "user_id":this.user_id,
                                        "page":this.page, //当前页
                                        "page_size":config.PAGE_SIZE,
                                    }
                        console.log("查询现金流水入参检查"+data);
                        const res=await this.$commonFunctions.check_bill(data);
                        if(res.code==20000){
                            this.total_spend=res.data.total_spend
                            this.total_income=res.data.total_income
                            console.log("查询现金流水入参检查"+(JSON.stringify(res.data)));
                            this.cash_transcation_set=[];
                            this.$nextTick(()=>{
                                console.log("当前表格的总页数："+res.data.max_size)
                                this.total_page_size=Number(res.data.max_size);
                                res.data.set.forEach(element => {
                                    element=this.replace_val(element,'cash')
                                    this.cash_transcation_set.push(element);
                                });
                                if(this.cash_transcation_set.length==config.PAGE_SIZE){
                                    this.page++;
                                    // this.stopQuery=false;
                                }else{
                                        this.page=1;
                                        // this.stopQuery=true;
                                    }
                                });
                                            
                        }else{
                                ElNotification({
                                    message: res.msg,
                                    title: "现金流水账单",
                                    type: "info",
                                    duration: 3000,
                                }); 
                            }
                                        
                    }else if(this.tab_active_name==="coupon"){
                        const data={"table_type":2,
                                    "period":this.period_value,
                                    "direction":this.direction_value,
                                    "user_id":this.user_id,
                                    "page":this.page, //当前页
                                    "page_size":config.PAGE_SIZE,
                                    }
                            console.log("查询优惠券流水入参检查"+data);
                            const res=await this.$commonFunctions.check_bill(data);
                            if(res.code==20000){
                                this.total_spend=res.data.total_spend   
                                this.total_income=res.data.total_income 
                                console.log("查询优惠券流水入参检查"+(JSON.stringify(res.data)))
                                    this.coupon_transcation_set=[];
                                    this.$nextTick(()=>{
                                        console.log("当前表格的总页数："+res.data.max_size)
                                        this.total_page_size=Number(res.data.max_size)
                                        res.data.set.forEach(element => {
                                        element=this.replace_val(element,'coupon')
                                        this.coupon_transcation_set.push(element);
                                    });
                                    if(this.coupon_transcation_set.length==config.PAGE_SIZE){
                                            this.page++;
                                            // this.stopQuery=false;
                                    }else{
                                            this.page=1;
                                            // this.stopQuery=true;
                                        }
                            });
                        }else{
                                ElNotification({
                                    message: res.msg,
                                    title: "优惠券流水账单",
                                    type: "info",
                                    duration: 3000,
                                }); 
                            }
                    }
                }
            }    
        },

        replace_val(element,type){
                if(type=='cash'){
                    if (parseInt(element['transcation_type'])===1){
                        element['transcation_type']='消费'
                    }else if(parseInt(element['transcation_type'])===2){
                        element['transcation_type']='退款'
                    }else if(parseInt(element['transcation_type'])===3){
                        element['transcation_type']='系统冲销'
                    }else if(parseInt(element['transcation_type'])===4){
                        element['transcation_type']='充值'
                    }

                    if(parseInt(element['transcation_direction'])===1){
                        element['transcation_direction']='收入'
                        console.log(element['transcation_direction'])
                    }else if(parseInt(element['transcation_direction'])===2){
                        element['transcation_direction']='支出'
                    }
                }else if(type=='coupon'){
                    if (parseInt(element['transcation_type'])===1){
                        element['transcation_type']='过期核销'
                    }else if(parseInt(element['transcation_type'])===2){
                        element['transcation_type']='使用核销'
                    }else if(parseInt(element['transcation_type'])===3){
                        element['transcation_type']='管理员核销'
                    }else if(parseInt(element['transcation_type'])===4){
                        element['transcation_type']='推荐奖励'
                    }else if(parseInt(element['transcation_type'])===5){
                        element['transcation_type']='新人奖励'
                    }


                    if(parseInt(element['transcation_direction'])===1){
                        element['transcation_direction']='收入'
                    }else if(parseInt(element['transcation_direction'])===2){
                        element['transcation_direction']='支出'
                    }
                }

                const date = new Date(element['transcation_date']);  
                const year = date.getFullYear();  
                const month = String(date.getMonth() + 1).padStart(2, '0');  
                const day = String(date.getDate()).padStart(2, '0');  
                const hours = String(date.getHours()).padStart(2, '0');  
                const minutes = String(date.getMinutes()).padStart(2, '0');  
                const seconds = String(date.getSeconds()).padStart(2, '0');  
                element['transcation_date']=`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                
                console.log(element)
                return element;
            },
        },
    }
                        
      
         
     </script>
     
     <style scoped>
     div#app{
        text-align: left;
     }
     .charge_summary{
        height: 40px;
        background-color: #f0f2f5;
        align-content: center;
        font-size: 10pt;
     }
     .charge_button{
      float: right;
      margin-right: 5dvw;
     }
     .coupon_button{
        border: 0;
        padding-left: 0;
        font-size: var(--el-collapse-content-font-size);
        font-weight: bold;
     }
     .coupon_button:hover{
        background-color: transparent;
     }
     span.balance{
        margin-left: 2dvw;
     }
     .is-error{
        color:#dd2f18;
        font-size: 10pt;
     }
    .promotion_code{
        margin-left:2dvw;
        color:blue;
        font-weight: 600;
        font-size: 14pt;
    }
     .page_title{
         display:block; 
         font-weight: bold;
         font-size: 100%;
         letter-spacing: .25px;
         margin: 2dvh 2dvw;
         outline: 0;
         padding-bottom: 4px;
         padding-top: 8px;
     }
     .group_panel{
        border-radius: 10px; 
        box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.24); 
     }
     .avatar{
        border-radius: 20px;
        width: 40px;
        height: 40px;
     }
    img.avatar{
     margin-right: 20px;;    
    }
    div.avatar-uploader{
        margin-bottom: 20px;
    }
    
     .nick_name{
        margin: 10px;
        font-weight: 400;
     }
     .edit_button{
        margin-top:5px ;
        margin-left: 67.5dvw;
     }
     .back_home{
        margin-top: 25dvh;
        margin-left: 30dvw;
        width: 40dvw;
     }
     div.my_property_collapse{
        padding-left: 2.5dvw;       
     }
    
     div.selected{
        border: 1px solid  #409eff;
        color: #409eff;
        font-weight: bold;
     }
    
     .summarize{
        margin-left:15px ;
     }
     </style>